package com.qf.thread.then;

import java.util.concurrent.*;

public class ThenRunDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                20,
                2000,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // 启动一个异常任务去执行，有返回值
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程1进来了，开始休眠");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程1休眠结束");
            return "ok";
        }, executor)
//                .thenRunAsync(() -> { // 等线程1执行完后，在来执行线程2
//                    System.out.println("线程2不需要依赖线程1的结果");
//                }, executor)
//                .thenAcceptAsync((resp) -> { // 等线程1执行完后在来执行,可以接收线程1的结果，但是不能有返回值
//                    System.out.println("线程3依赖线程1的返回值：" + resp);
//                }, executor);
                .thenApplyAsync((resp) -> {
                    System.out.println("线程4接收线程1的返回值【" + resp + "】，并且这里有返回值");
                    return "baibai";
                }, executor);

        String s = future.get();
        System.out.println(s);
    }
}
